#include "qssdebugkeypresseater.h"
#include "qboxlayout.h"
#include "qdialog.h"
#include "qtextedit.h"

#ifdef SPARK_FEATURE_ANALYZER
    #include <analyzer.h>
#endif

QssDebugKeyPressEater::QssDebugKeyPressEater(QWidget *parent, bool usedialog, Qt::Key pressKey)
    : QObject(parent)
    , m_pressKey(pressKey)
    , m_target(parent)
    , m_editinit(false)
    , m_usedialog(usedialog)
{
//    m_textedit->setWindowFlag(Qt::WindowStaysOnTopHint, true);

    if (usedialog)
    {
        m_dialog = new QDialog;
        m_dialoglayout = new QVBoxLayout(m_dialog);
        m_textedit = new QTextEdit(m_dialog);
        m_dialoglayout->addWidget(m_textedit);
    }
    else
    {
        m_textedit = new QTextEdit;
        m_mapedit = new QTextEdit;
        auto font = m_mapedit->font();
#if QT_VERSION < QT_VERSION_CHECK(5, 13, 0)
        font.setFamily(QString::fromUtf8("Noto Mono"));
#else
        font.setFamilies({QString::fromUtf8("Noto Mono")});
#endif
        m_mapedit->setFont(font);
    }

    if (parent)
    {
        parent->installEventFilter(this);
    }
    else
        deleteLater();
}

QssDebugKeyPressEater::QssDebugKeyPressEater(QObject *parent, QWidget *target, bool usedialog, Qt::Key pressKey)
    : QObject(parent)
    , m_pressKey(pressKey)
    , m_target(target)
    , m_editinit(false)
    , m_usedialog(usedialog)
{
    if (usedialog)
    {
        m_dialog = new QDialog;
        m_dialoglayout = new QVBoxLayout(m_dialog);
        m_textedit = new QTextEdit(m_dialog);
        m_dialoglayout->addWidget(m_textedit);
    }
    else
    {
        m_textedit = new QTextEdit;
        m_mapedit = new QTextEdit;
        auto font = m_mapedit->font();
#if QT_VERSION < QT_VERSION_CHECK(5, 13, 0)
        font.setFamily(QString::fromUtf8("Noto Mono"));
#else
        font.setFamilies({QString::fromUtf8("Noto Mono")});
#endif
        m_mapedit->setFont(font);
    }

    if (parent)
    {
        parent->installEventFilter(this);
    }
    else
        deleteLater();
}

bool QssDebugKeyPressEater::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::KeyPress)
    {
        if ((static_cast<QKeyEvent *>(event))->key() == m_pressKey)
        {
            if (m_editinit == false)
            {
                m_textedit->setText(m_target->styleSheet());
                connect(m_textedit, &QTextEdit::textChanged, [this]()
                {
                    m_target->setStyleSheet(m_textedit->toPlainText());
                });
                m_editinit = true;

#ifdef SPARK_FEATURE_ANALYZER
                m_mapedit->setText(Analyzer::analyzerJson(m_target));
#endif
            }
            if (m_usedialog)
            {
                m_dialog->exec();
            }
            else
            {
                m_textedit->show();
#ifdef SPARK_FEATURE_ANALYZER
                m_mapedit->show();
#endif
            }
        }
    }
    return QObject::eventFilter(watched, event);
}
